<?php

namespace app\admin\controller\mall\goods;

use app\admin\controller\mall\Base;
use think\Db;
use fast\Random;
use think\Config;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 商品
 *
 * @icon fa fa-circle-o
 */
class Goods extends Base
{
    
    /**
     * Goods模型对象
     * @var \app\common\model\mall\goods\Goods
     */
    protected $model = null;

    /**
     * Shop所属用户
     * @var \app\common\model\mall\goods\Goods
     */
    protected $shop_user_id = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\mall\goods\Goods;
        $this->view->assign("goodstypeList", $this->model->getGoodstypeList());
        $this->view->assign("freighttypeList", $this->model->getFreighttypeList());
        $this->view->assign("statusList", $this->model->getStatusList());

    }

    /**
     * 导入淘宝商品
     */
    public function gettbgoods($ids = NULL)
    {
        $row = $this->model->get($ids);
        $this->shop_user_id = \app\common\model\mall\shop\Shop::getFieldById($row['shop_id'],'user_id');
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }

                    @set_time_limit(600);
                    //正则提取宝贝id
                    $url = $params['tbid'];
                    $pattern = "/[https|http]+\:\/\/[\w]+.[\w]+.com\/item.htm\?.*?id=([\d]+).*?/";
                    preg_match($pattern, $url, $tid);
                    if(isset($tid[1]) && $tid[1]){
                        $id = $tid[1];
                    }else{
                        $id = $params['tbid'];
                    }
                    if(!$id) {
                        $this->error('没有获取到宝贝ID，请重新输入！');
                    }
                    //获取淘宝商品详情图片的接口
                    $json = $this->file_get_contents_curl("https://hws.alicdn.com/cache/mtop.wdetail.getItemDescx/4.1/?data=%7B%22item_num_id%22%3A%22{$id}%22%7D");
                    $data = json_decode($json,1);
                    if($data['data']['pages']){
                        $content = "";
                        foreach($data['data']['pages'] as $p){
                            $content .= $p;
                        }
                        //获取宝贝详情图片
                        $content = str_replace("<img>",'<img src="',$content);
                        $content = str_replace("</img>",'">',$content);
                        $content = str_replace("txt","p",$content);

                        if($params['isbodyimg']){
                            //处理宝贝详情图片：下载到服务器
                            //step1.匹配详情中的所有图片地址数组，并进行数组循环
                            $pattern = "/((https|http|ftp|rtsp|mms)?:\/\/)[^\s]+?(.gif|.jpg|.jpeg|.png)/";
                            $isMatched = preg_match_all($pattern, $content,$goods_body);
                            if($isMatched && isset($goods_body[0])) $goods_body = array_unique($goods_body[0]);//本地图片数组
                            if(is_array($goods_body) && !empty($goods_body)){
                                $i = 0;
                                foreach($goods_body as $v){
                                    if($v != ''){
                                        //step2.逐个图片上传，并进行正文替换
                                        $bodyimage = $this->download($v);//调用下载图片函数
                                        $bodyimage = $bodyimage['path'] . $bodyimage['name'];//实际图片地址
                                        //开始替换详情图片地址
                                        $content = str_replace($v,$bodyimage,$content);
                                        $i++;
                                    }
                                }
                            }
                        }
                    }
                    if($content){
                        $html = file_get_contents("http://item.taobao.com/item.htm?id={$id}");
                        preg_match("/<body[^>]*>(.*?)<\/body>/is", $html, $body);
                        $text = iconv('GBK','UTF-8//IGNORE',$body[1]);
                        unset($html,$body);
                        //页面标签主图
                        preg_match("/<ul id=\"J_UlThumb\" class=\"tb-thumb[^>]*\">(.*?)<\/ul>/is", $text, $goodsImgUl);
                        //页面标签标题(淘宝)
                        preg_match("/<h3[^r]+class=\"tb-main-title\" data-title=\"([^\"]+)\"[^>]*>/", $text, $goodsTitle);
                        //页面标签标题(天猫)
                        preg_match("/<h1 data-spm=\"1000983\">([^<]*?)<\/h1>\s*<p>([^<]*?)<\/p>/", $text, $goodsTitle2);
                        //页面标签价格
                        preg_match("/<em class=\"tb-rmb-num\">([1-9]\d*.\d*|0.\d*[1-9]\d*)<\/em>/", $text, $goodsPrice);
                        //页面标签规格图
                        preg_match("/<ul[^>]*class=\"[^>]*J_TSaleProp tb-img[^>]*\"[^>]*>(.*?)<\/ul>/is", $text, $goodsSaleImgUl);
                        //主图地址
                        if(isset($goodsImgUl[1])) preg_match_all("/<img[^r]+src=\"([^\"]+)\"[^>]*>/", $goodsImgUl[1], $goodsImgs);
                        //规格地址
                        if(isset($goodsSaleImgUl[1])) preg_match_all("/<a href=\"[^>]*\" style=\"background:url\(([^\"]+)\) center no-repeat;\"[^>]*>/", $goodsSaleImgUl[1], $goodsSaleImgs);
                        unset($text,$goodsImgUl,$goodsSaleImgUl);
                        if(isset($goodsSaleImgs[1])){
                            $goodsImgs[1] = array_merge($goodsImgs[1], $goodsSaleImgs[1]);
                            unset($goodsSaleImgs);
                        }
                        //获取商品主图
                        $imgArr = array();
                        foreach ($goodsImgs[1] as $img) {
                            $img = substr($img,0,strrpos($img,"_"));
                            $temp = $this->download("http:" . $img);
                            $imgArr[] = $temp['path'] . $temp['name'];
                        }
                        unset($goodsImgs);

                        //开始导入数据
                        if($params['do']){
                            $update_common = array();
                            $update_common['id'] = $ids;
                            //标题
                            if($params['istitle'] && (isset($goodsTitle[1])||isset($goodsTitle2[1]))) {
                                $title = isset($goodsTitle[1]) ? $goodsTitle : $goodsTitle2;
                                $update_common['goodsname'] = trim($title[1]);
                                $update_common['goodstips'] = trim(isset($title[2]) ? $title[2] : $title[1]);
                            }
                            //价格
                            if($params['isprice'] && isset($goodsPrice[1])){
                                $update_common['shopprice'] = $goodsPrice[1];
                                $update_common['marketprice'] = round($goodsPrice[1]*1.1,0);
                            }
                            //主图
                            if(isset($imgArr[0])){
                                $update_common['goodsimg'] = $imgArr[0];
                                unset($imgArr[0]);
                                if(count($imgArr)>0)
                                    $update_common['gallery'] = implode(",",$imgArr);
                            }
                            //详情
                            $update_common['goodsdesc'] = $content;

                            // 删除宝贝原图
                            $old_goods_body = $row['goodsdesc'].",".$row['goodsimg'].",".$row['gallery'];
                            if(!empty($old_goods_body)){
                                //匹配出详情中要删除的图片名称
                                $pattern = "/(\/uploads)[^\s]+?(.gif|.jpg|.jpeg|.png)/";//仅url图片名称的正则表达式
                                $isMatched = preg_match_all($pattern,$old_goods_body,$oldImg_arr);
                                if($isMatched) $oldImg_arr = array_unique($oldImg_arr[0]);
                                if(!empty($oldImg_arr) && is_array($oldImg_arr)){
                                    //删除附件表中的图
                                    $id_arr = db('Attachment')->where(["url"=>['in',$oldImg_arr], 'user_id' => $this->shop_user_id])->column("id");
                                    if($id_arr) {
                                        \think\Hook::add('upload_delete', function ($params) {
                                            $attachmentFile = ROOT_PATH . '/public' . $params['url'];
                                            if (is_file($attachmentFile)) {
                                                @unlink($attachmentFile);
                                            }
                                        });
                                        $attachmentlist = model('Attachment')->where('id', 'in', $id_arr)->select();
                                        foreach ($attachmentlist as $attachment) {
                                            \think\Hook::listen("upload_delete", $attachment);
                                            $attachment->delete();
                                        }
                                    }
                                }else{
                                    echo "<script>alert('没有找到要删除的原图名称');</script>";
                                }
                            }else{
                                echo "<script>alert('没有读取到详情原内容');</script>";
                            }
                        }
                    }
                    $result = $row->allowField(true)->save($update_common);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    //补充删除未进入附件表的图
                    foreach ($oldImg_arr as $attachment){
                        $attachmentFile = ROOT_PATH . '/public' . $attachment;
                        if (is_file($attachmentFile)) {
                            @unlink($attachmentFile);
                        }
                    }
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 下载远程商品图片
     * @param string $url 下载的图片
     * @return bool
     */
    public function download($url)
    {
        if (empty($url)) {
            $this->error(__('下载地址不能为空！'));
        }
        $temp = explode('.',$url);
        $temp = array_reverse($temp);
        $suffix = $temp[0];
        //$temp = $temp[1];
        //$temp = explode('/',$temp);
        //$oldname = end($temp);
        $tmp_name = sprintf('%010d',time() - 946656000)
            . sprintf('%03d', microtime() * 1000)
            . sprintf('%04d', mt_rand(0,9999));
        //$pathname = TEMP_PATH . $oldname . "." . $suffix;

        $upload = Config::get('upload');

        preg_match('/(\d+)(\w+)/', $upload['maxsize'], $matches);
        $type = strtolower($matches[2]);
        $typeDict = ['b' => 0, 'k' => 1, 'kb' => 1, 'm' => 2, 'mb' => 2, 'gb' => 3, 'g' => 3];
        $size = (int)$upload['maxsize'] * pow(1024, isset($typeDict[$type]) ? $typeDict[$type] : 0);

        $mimetypeArr = explode(',', strtolower($upload['mimetype']));

        //验证文件后缀
        if ($upload['mimetype'] !== '*' && !in_array($suffix, $mimetypeArr)) {
            $this->error(__('下载文件格式受限制'));
        }
        $replaceArr = [
            '{year}'     => date("Y"),
            '{mon}'      => date("m"),
            '{day}'      => date("d"),
            '{hour}'     => date("H"),
            '{min}'      => date("i"),
            '{sec}'      => date("s"),
            '{random}'   => Random::alnum(16),
            '{random32}' => Random::alnum(32),
            '{filename}' => $tmp_name,
            '{suffix}'   => $suffix,
            '{.suffix}'  => $suffix ? '.' . $suffix : '',
            '{filemd5}'  => $tmp_name,
        ];
        $savekey = $upload['savekey'];
        $savekey = str_replace(array_keys($replaceArr), array_values($replaceArr), $savekey);

        $uploadDir = substr($savekey, 0, strripos($savekey, '/') + 1);
        $fileDir = str_replace("\\","/",ROOT_PATH) . 'public' . $uploadDir;
        $fileName = substr($savekey, strripos($savekey, '/') + 1);
        //创建保存目录
        if(!file_exists($fileDir) && !mkdir($fileDir,0777,true)){
            $this->error(__('存储目录不存在！'));
        }

        $pathname = $fileDir . $fileName;
        $img = $this->file_get_contents_curl($url);
        file_put_contents($pathname,$img);

        $file = new \think\File($pathname);
        unset($img,$temp);

        if (empty($file)) {
            $this->error(__('未下载文件或超出服务器下载限制'));
        }
        //验证文件大小
        if ($size < filesize($pathname)) {
            $this->error(__('文件大小受限制'));
        }

        //判断是否已经存在附件
        $sha1 = $file->hash();

        if ($file) {
            $imagewidth = $imageheight = 0;
            if (in_array($suffix, ['gif', 'jpg', 'jpeg', 'bmp', 'png', 'swf'])) {
                $imgInfo = getimagesize($pathname);
                $imagewidth = isset($imgInfo[0]) ? $imgInfo[0] : $imagewidth;
                $imageheight = isset($imgInfo[1]) ? $imgInfo[1] : $imageheight;
            }
            $params = array(
                'admin_id'    => 0,
                'user_id'     => $this->shop_user_id,
                'filesize'    => filesize($pathname),
                'imagewidth'  => $imagewidth,
                'imageheight' => $imageheight,
                'imagetype'   => $suffix,
                'imageframes' => 0,
                'mimetype'    => "image/".$suffix,
                'url'         => $uploadDir . $fileName,
                'uploadtime'  => time(),
                'storage'     => 'local',
                'sha1'        => $sha1,
            );
            $attachment = model("attachment");
            $attachment->data(array_filter($params));
            $attachment->isUpdate(false)->save();
            $data = array ();
            $data ['name']      = $fileName;
            $data ['path']      = $uploadDir;
            return $data;
        } else {
            // 下载失败获取错误信息
            $this->error($file->getError());
        }
    }

    /**
     * 获取网页内容
     */
    private  function file_get_contents_curl($url){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
        //curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, true); // 从证书中检查SSL加密算法是否存在
        curl_setopt ($ch, CURLOPT_URL, $url);
        curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT,15);
        $dxycontent = curl_exec($ch);
        curl_close($ch);
        return $dxycontent;
    }

    public function selectpage()
    {
        return parent::selectpage();
    }

}
